from django.shortcuts import render
import requests
import time
import random
import hashlib

proxies = {
  "https": "http://10.8.0.1:8080",
}

def get_access_token(appid, appsecret):
    url = f"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appid}&secret={appsecret}"
    response = requests.get(url,proxies=proxies, verify=False)
    data = response.json()
    return data.get('access_token')

def get_jsapi_ticket(access_token):
    url = f"https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={access_token}&type=jsapi"
    response = requests.get(url,proxies=proxies, verify=False)
    data = response.json()
    return data.get('ticket')

def create_signature(jsapi_ticket, nonce_str, timestamp, url):
    string_to_sign = f"jsapi_ticket={jsapi_ticket}&noncestr={nonce_str}&timestamp={timestamp}&url={url}"
    sha1 = hashlib.sha1()
    sha1.update(string_to_sign.encode('utf-8'))
    return sha1.hexdigest()


def verify(request):
    appid = 'wxaa19b1f8d361a0b4'
    appsecret = '3bc65fe92930a87be8024ef98561c553'
    access_token = get_access_token(appid, appsecret)
    jsapi_ticket = get_jsapi_ticket(access_token)

    timestamp = int(time.time())
    nonce_str = ''.join(random.choice('abcdefghijklmnopqrstuvwxyz0123456789') for _ in range(15))
    url = 'https://api.zjcxjc.cn/api/v1/doc/verify'

    signature = create_signature(jsapi_ticket, nonce_str, timestamp, url)

    context = {
        'appId': appid,
        'timestamp': timestamp,
        'nonceStr': nonce_str,
        'signature': signature,
    }
    return render(request, 'scan_qr.html', context)
